
import cv2
from ultralytics import YOLO
import easyocr
import numpy as np

class AdvancedPlateRecognizer:
    def __init__(self, model_path='best.pt'):
        self.model = YOLO(model_path)
        self.reader = easyocr.Reader(['ch_sim', 'en'], gpu=False)
    
    def detect_and_recognize(self, image_path):
        # 使用YOLO检测车牌
        results = self.model(image_path)
        
        plate_results = []
        for result in results:
            boxes = result.boxes
            for box in boxes:
                x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
                
                # 提取车牌区域
                plate_img = cv2.imread(image_path)[int(y1):int(y2), int(x1):int(x2)]
                
                # 使用EasyOCR识别车牌文字
                ocr_result = self.reader.readtext(plate_img)
                if ocr_result:
                    plate_results.append({
                        'text': ocr_result[0][1],
                        'confidence': ocr_result[0][2],
                        'bbox': (x1, y1, x2, y2)
                    })
        
        return plate_results

# 使用示例
if __name__ == "__main__":
    advanced_recognizer = AdvancedPlateRecognizer()
    results = advanced_recognizer.detect_and_recognize('test_car.jpg')
    print(results)
